import { Injectable } from '@angular/core';
// import { HttpClient, HttpErrorResponse, HttpHeaders,HttpResponse } from '@angular/common/http';
import { Observable, TimeoutError } from 'rxjs';
import * as constants from './Constants'
import { Logger } from './Logger';

import { environment } from '../../environments/environment';
import { NativeService } from './NativeService';
import { Helper } from './Helper';
import { Utils } from './Utils';
import { HttpHelper, RequestSetting } from './HttpHelper';
import { log } from 'util';
import { HTTP } from '@ionic-native/http/ngx';
import { CookieService } from 'ngx-cookie-service';
import { Storage } from './Storage';
import { NavController, LoadingController } from '@ionic/angular';
import { ActivatedRoute, Router } from '@angular/router';
// declare const require: any; // <-- 新增
import { HttpClient, HttpHeaders } from "@angular/common/http";

/**
 * 封装angular http
 */
@Injectable({
    providedIn: 'root'
})
export class HttpService extends HttpHelper {
    constructor(public http: HTTP,
        private httpClient: HttpClient,
        public helper: Helper,
        public cookie: CookieService,
        public loadingController: LoadingController,
        public nav: NavController,
        private mRouter: Router,
        private route: ActivatedRoute,
        public native: NativeService) {

        super(helper, nav);

        //   this.http.setSSLCertMode
    }



    public get(url: string, params: any = {}, setting: RequestSetting = {
        showLoading: false
    }) {
        const options = {
            method: 'GET',
            url: url,
            params
        };
        return this.doRequest(options, setting, "");
    }

    public post(url: string, body: any = {}, setting: RequestSetting = {}): Observable<any> {
        const options = {
            method: 'POST',
            data: body,
            serializer: 'json',
            headers: {}
        };

        return this.doRequest(options, setting, url);
    }

    public getParameter(url: string, params) {
        let index = url.lastIndexOf('?');
        url = url.substring(index + 1, url.length);
        let arr = url.split('&');
        let str = '';
        for (let index = 0; index < arr.length; index++) {
            const element = arr[index];
            let obj = element.split('=');
            let data = null;
            obj.forEach((element1, idx) => {
                if (element1 == params) {
                    data = obj;
                }
            });
            if (data != null) {
                return data[1];
            }
        }
        return "";
    }
    public getParameterUrl(url: string) {
        let index = url.lastIndexOf('?');
        url = url.substring(0, index);
        return url;
    }

    public getImageUrl() {
        // downloadFile  //下载文件接口
        //downloadZipImg   //下载图片压缩过
        return environment.fileServerUrl + 'file/downloadZipImg?fileUuid=';


    }


    public getSendBody(url): Observable<any> {
        return Observable.create(observer => {
            if (this.helper.isMobile()) {
                this.http.get(url, {}, {}).then((res: any) => {
                    observer.next(JSON.parse(res.data));
                }).catch(err => {
                    observer.error(JSON.stringify({ 'code': '404' }))
                })
            } else {
                this.httpClient.get(url).toPromise().then(res => {
                    observer.next(res);
                }).catch(err => {
                    observer.error(JSON.stringify({ 'code': '404' }))
                })
            }

        });
    }

    public delete(url: string, params: any = {}, setting: RequestSetting = {}) {
        const options = {
            method: 'DELETE',
            url: url,
            params
        };
        return this.doRequest(options, setting, "");
    }

    public doRequest(options, setting: RequestSetting, url: string, httpUrl: number = 0) {
        const defaultSetting = HttpHelper.getDefaultSetting(setting);

        if (this.isSetSSlCertMode()) {
            this.isSetSSlCertMode()
        }
        return this.defaultRequest(options, defaultSetting, url, httpUrl);
    }


    isSetSSlCertMode(): boolean {
        let is = false;
        // this.http.setSSLCertMode('nocheck').then(res => {
        //     is = false;
        // }).catch(err => {
        //     this.http.setSSLCertMode('nocheck').then(res => {
        //         is = false;
        //     }).catch(err => {
        //         is = true;
        //     })
        // })
        return is;
    }


    /**
     * 一个app可能有多个后台接口服务(api),针对主api添加业务处理
     */
    public defaultRequest(options, set: RequestSetting, url: string, httpUrl: number = 0): Observable<any> {
        const setting = HttpHelper.getDefaultSetting(set);
        if (constants.isDebug) {
            console.log('Loggerurl=====', url);
        }
        return Observable.create(observer => {
            let isLogin = false;
            let token = Storage.localStorage.get("userPhone");
            // if (!constants.IS_TEST) {
                for (const key in constants.ApiServeLogin) {
                    if (constants.ApiServeLogin[key] == url) {
                        if (!token) {
                            let routerUrl = this.mRouter.url;
                            isLogin = true;
                        }
                    }
                }
            // }
            this.requestBefore(options, setting);
            if (isLogin) {
                this.requestError({}, false)
                observer.error('');
                return
            }
            if (httpUrl == 0) {
                url = environment.appServerUrl + url;
                this.http.setHeader(url, 'Content-type', 'application/json');
            } else {
                this.http.setHeader(url, 'Content-type', 'application/octet-stream');
                url = url;
            }

            let storage = Storage.localStorage.get("cId");
            if (storage) {
                this.http.setCookie(url, storage);
            }
            this.http.setRequestTimeout(constants.HTTP_TIME);
            let option = options;
            console.log('请求地址url==',url);
            
            if (this.helper.isMobile()) {
                this.http.sendRequest(url, option).then(res => {
                    this.requestSuccess(res.data, setting.showLoading)
                    let cookie = res.headers['set-cookie']
                    if (cookie) {
                        let getCookieData = this.getCookie(cookie);
                        if (getCookieData) {
                            Storage.localStorage.set("cId", getCookieData)
                        }
                    }
                    // }

                    observer.next(JSON.parse(res.data))
                }).catch(err => {
                    this.requestError(err)
                    observer.error(this.requestFailedHandle(options.url, err));
                });
            } else {
                this.httpClient.post(url, option.data).toPromise().then((res: any) => {
                    this.requestSuccess(res, setting.showLoading)
                    observer.next(res)
                }).catch(err => {
                    this.requestError(err)
                    observer.error(this.requestFailedHandle(options.url, err));
                })

            }
        });
    }
     presentLoadingWithOptions() {
        let loading=null;
         loading =  this.loadingController.create({
            //   duration: 5000,
            message: '',
            //   translucent: true,
            //   cssClass: 'custom-class custom-loading'
        });
        return  loading.present();
    }
    public request(ops, set: RequestSetting): Observable<any> {
        const options = {
            url: '',
            method: 'POST',
            body: null,
            params: null,
            urlWithParams: false,
            headers: null,
            reportProgress: false,
            withCredentials: false,
            responseType: 'json',
            ...ops
        };

        const setting = HttpHelper.getDefaultSetting(set);
        options.url = Utils.formatUrl(options.url);
        return Observable.create(observer => {
            // 如果需要缓存，先尝试从sessionStorage中取数据
            if (setting.needCache) {
                const cacheResult = HttpHelper.getCacheData(options);
                if (cacheResult) {
                    observer.next(cacheResult);
                    return;
                }
            }
            this.requestBefore(options, setting);
            // this.http.request(options.method, options.url, {})
            //     .pipe(timeout(environment.requestTimeout))
            //     .subscribe(res => {
            //         setting.needCache && HttpHelper.setCacheData(options, res); // 如果需要缓存，保存数据到sessionStorage中
            //         this.requestSuccess(options);
            //         observer.next(res);
            //     }, err => {
            //         this.requestError(options);
            //         observer.error(this.requestFailedHandle(options.url, err));
            //     });

        });
    }




    /** 
     * 获取cookie
     */
    // public getCookie1(cookie: string) {
    //     cookie = cookie.replace(/\s*/g, "");
    //     let cId = "";
    //     let ck = cookie.split(";");
    //     for (const key in ck) {
    //         let c = ck[key].trim().substring(0, 3)
    //         if (c == 'cId') {
    //             cId = ck[key];
    //         }
    //     }
    //     return cId;
    // }
    public getCookie(cookie: string) {
        cookie = cookie.replace(/\s*/g, "");
        let cId = "";
        let ck = cookie.split(";");
        for (const key in ck) {
            let HttpOnly = ck[key].trim().substring(0, 9);
            let cookieData = ck[key].trim();
            if (HttpOnly == 'HttpOnly,') {
                cookieData = cookieData.replace('HttpOnly,', '')
            }
            let c = cookieData.substring(0, 3)
            if (c == 'cId') {
                cId = cookieData;
            }
        }
        return cId;
    }
    // : Response
    /**
     * 处理请求失败事件
     */
    // private requestFailedHandle(url: string, err: HttpErrorResponse) { // : Response
    private requestFailedHandle(url: string, err: any) { // : Response
        const status = err.status;
        let msg = '请求发生异常，请联系管理员';
        // 与后台约定，状态码为400即为业务异常
        // if (status === 400||status === 502) {
        if (status === 502) {
            const errData = err.error;
            //  401 token无效或过期需要重新登录
            // let pass = Storage.localStorage.get('user_password');
            // let phone = Storage.localStorage.get('userPhone');
            // Storage.localStorage.clear();
            // Storage.sessionStorage.clear();
            // if (pass) {
            //     Storage.localStorage.set('user_password', pass);
            // }
            // if (phone) {
            //     Storage.localStorage.set('userPhone', phone);
            // }
            msg = 'Re-login'
            // let data = {
            //     userPhone: this.signInfo.userPhone,
            //     userPassWord: this.signInfo.userPassWord,
            //     // code: this.signInfo.code
            //   }
            Storage.localStorage.clear();
            this.nav.navigateForward('/login');
            this.helper.toast(errData.msg || msg);
            // this.helper.alert('提示', errData.msg || msg);
            return errData;
        } else if (status === 400) {
            this.helper.toast("Network anomaly");
        } else {
            if (this.helper.isMobile()) {
                // this.helper.alert('请连接网络');
                // this.helper.toast('服务器连接失败，请联系管理员');
                if (status === 0) {
                    msg = '可能后台服务未启用';
                } else if (status === 404) {
                    msg = status + ' 未找到请求地址';
                } else if (status === 500) {
                    msg = status + ' 服务器出错，请稍后再试';
                }
                this.helper.alert('请求失败', "Network anomaly");
                // this.helper.toast(msg);
                Logger.http(err, {
                    url,
                    status
                });
            } else if (err instanceof TimeoutError) {
                this.helper.toast('request timeout!');
                // this.helper.alert('提示', '请求超时,请稍后再试!');
            } else {
                if (status === 0) {
                    msg = '可能后台服务未启用';
                } else if (status === 404) {
                    msg = status + ' 未找到请求地址';
                } else if (status === 500) {
                    msg = status + ' 服务器出错，请稍后再试';
                }
                this.helper.alert('请求失败', "Network anomaly");
                // this.helper.toast(msg);
                Logger.http(err, {
                    url,
                    status
                });
            }
        }
        return err;
    }

}
